package org.genntii.warehousesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.genntii.warehousesystem.domain.entity.Cart;
import org.genntii.warehousesystem.domain.entity.Goods;
import org.genntii.warehousesystem.domain.vo.CartVO;
import org.genntii.warehousesystem.mapper.CartMapper;
import org.genntii.warehousesystem.mapper.GoodsMapper;
import org.genntii.warehousesystem.mapper.GoodsWarehouseMapper;
import org.genntii.warehousesystem.service.CartService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsWarehouseMapper goodsWarehouseMapper;

    @Override
    public void add(int userId, int goodsId, BigDecimal price, int num) {
        Cart cart = Cart.builder().userId(userId).goodsId(goodsId)
                .addCartPrice(price).num(num).createTime(LocalDateTime.now()).build();
        cartMapper.insert(cart);
    }

    @Override
    public void del(int id) {
        cartMapper.deleteById(id);
    }

    @Override
    public void setNum(int id, int num) {
        cartMapper.setNum(num,id);
    }

    @Override
    public Cart cartExists(int userId, int goodsId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("goods_id",goodsId);
        return cartMapper.selectOne(wrapper);
    }

    @Override
    public List<CartVO> showAllCart(int userId) {
        List<Cart> carts = cartMapper.showAll(userId);
        List<CartVO> voList = new ArrayList<>();
        for (Cart cart:carts){
            Goods goods = goodsMapper.selectById(cart.getGoodsId());
            CartVO vo = CartVO.builder().id(cart.getId()).name(goods.getName()).goodsId(cart.getGoodsId())
                    .addPrice(cart.getAddCartPrice()).imgSrc(goods.getImgSrc())
                    .price(goods.getOutPrice()).num(cart.getNum())
                    .goodsWarehouseList(goodsWarehouseMapper.listGoodsWarehouse(cart.getGoodsId()))
                    .build();
            voList.add(vo);
        }
        return voList;
    }
}
